package server

import (
	"crypto/rsa"
	"crypto/tls"
	"fmt"
	"os"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type (
	HttpServerProperties struct {
		PermitCNs   []string      `env:"PERMIT_CNS"`
		Address     string        `env:"ADDRESS,notEmpty"`
		ReadTimeout time.Duration `env:"READ_TIMEOUT" envDefault:"5s"`
		TLS         TLSProperties `envPrefix:"TLS_"`
	}

	TLSProperties struct {
		CertPath string `env:"CERT_PATH"`
		KeyPath  string `env:"KEY_PATH"`
	}
)

func (properties *TLSProperties) ToConfig() (*tls.Config, error) {
	if properties.KeyPath == "" || properties.CertPath == "" {
		return nil, nil
	}

	pair, err := tls.LoadX509KeyPair(properties.CertPath, properties.KeyPath)
	if err != nil {
		return nil, fmt.Errorf("cannot load pair: %w", err)
	}

	tlsConfig := new(tls.Config)
	tlsConfig.Certificates = []tls.Certificate{pair}

	return tlsConfig, nil
}

func (properties *TLSProperties) ToRSAKeys() (*rsa.PublicKey, *rsa.PrivateKey, error) {
	cert, err := os.ReadFile(properties.CertPath)
	if err != nil {
		return nil, nil, fmt.Errorf("public key not found at '%s': %w", properties.CertPath, err)
	}

	publicKey, err := jwt.ParseRSAPublicKeyFromPEM(cert)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to parse public key: %w", err)
	}

	key, err := os.ReadFile(properties.KeyPath)
	if err != nil {
		return nil, nil, fmt.Errorf("private key not found at '%s': %w", properties.KeyPath, err)
	}

	privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to parse private key: %w", err)
	}

	return publicKey, privateKey, nil
}
